package com.intelligentclass.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.intelligentclass.constant.UserType;
import com.intelligentclass.entity.Notice;
import com.intelligentclass.mydata.MyJson;
import com.intelligentclass.services.NoticeService;
import com.intelligentclass.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/notice")
@CrossOrigin(origins = "*")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    // 获取所有公告
    @GetMapping("/all")
    public ResponseEntity<List<Notice>> getAllNotices() {
        try {
            List<Notice> notices = noticeService.getAllNotices();
            return ResponseEntity.ok(notices);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    // 根据CID获取公告
    @GetMapping("/by-cid/{cid}")
    public ResponseEntity<?> getNoticesByCid(@PathVariable("cid") String cid) {
        try {
            List<Notice> notices = noticeService.getNoticesByCid(cid);
            if (notices.isEmpty()) {
                return ResponseEntity.status(404).body("No notices found for cid: " + cid);
            }
            return ResponseEntity.ok(notices);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Error retrieving notices: " + e.getMessage());
        }
    }

    // 新增公告
    @PostMapping("/add")
    public ResponseEntity<?> addNotice(@RequestParam("title") String title,
                                       @RequestParam("text") String text,
                                       @RequestParam("noticeCid") String noticeCid) {
        try {
            // 创建新的 Notice 对象
            Notice notice = new Notice();
            notice.setNoticeTitle(title);
            notice.setNoticeText(text);
            notice.setNoticeCid(noticeCid);

            // 保存公告
            Notice savedNotice = noticeService.addNotice(notice);

            return ResponseEntity.ok(savedNotice);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Error creating notice: " + e.getMessage());
        }
    }

    @PostMapping("/getCurrentWeek")
    public ResponseEntity<?> getCurrentWeek(@RequestHeader Map<String, String> header) {
        MyJson json = new MyJson();
        String token = header.get("token");
        DecodedJWT jwt;
        int usertype;
        try{
            jwt = JWTUtil.verifyToken(token);
            usertype = jwt.getClaim("usertype").asInt();
            if(usertype != UserType.TEACHER && usertype != UserType.STUDENT) {
                json.setMessage("Insufficient permissions");
                json.setStatus(403);
                json.addData("status", -1);
                return ResponseEntity.badRequest().body(json);
            }
        }
        catch(TokenExpiredException e){
            json.setMessage("Token has expired");
            json.setStatus(403);
            json.addData("status", -2);
            return ResponseEntity.badRequest().body(json);
        }
        catch(Exception e){
            json.setMessage("Unexpected error");
            json.setStatus(500);
            json.addData("status", -1);
            return ResponseEntity.badRequest().body(json);
        }

        LocalDate start = LocalDate.of(2024, 9, 2);
        LocalDate current = LocalDate.now();
        long daysBetween = ChronoUnit.DAYS.between(start, current);
        int week = (int) (daysBetween/7);
        

        json.setMessage("Success");
        json.setStatus(200);
        json.addData("week", week);
        return ResponseEntity.ok(json);
    }
}
